package com.before.servlet;

import com.before.dao.StudentDao;
import com.before.dao.StudentDaoImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/stujson")
public class StudentJsonServlet extends HttpServlet {

    StudentDao studentDao = new StudentDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        //获取输出流
        PrintWriter writer = resp.getWriter();
        List<String> names = studentDao.getAll();
        //把列表转为json
        Gson gson = new Gson();
        String json = gson.toJson(names);
        System.out.println(json);
        //把json写入流
        writer.write(json);
        writer.close();
    }
}
